package com.nie.mall.gateway.handler;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.nie.mall.gateway.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 网关异常处理程序
 *
 * @author nie_cq
 * @date 2023/02/03
 */
@Configuration
@Order(-1)
@Slf4j
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    /**
     * 处理
     *
     * @param serverWebExchange 服务器网络交换
     * @param throwable         throwable
     * @return {@code Mono<Void>}
     */
    @Override
    public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
        ServerHttpResponse response = serverWebExchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(throwable);
        }
        if (throwable instanceof NotFoundException) {
            throw ExceptionUtil.wrapRuntime("服务为找到");
        }
        log.error("异常：{}",throwable.getMessage());
        log.error("[网关异常处理]请求路径:{},异常信息:{}", serverWebExchange.getRequest().getPath(),throwable.getMessage());
        return ResponseUtil.returnMono(response,throwable.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
